package com.example.chat.server.server;

import com.example.chat.server.handler.ChatServerHandler;
import com.example.chat.server.handler.HeartBeatServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class ChatServer {

    @Value("${netty.port:8080}")
    private int port;

    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;
    private Channel channel;

    @Autowired
    private ChatServerHandler chatServerHandler;

    /**
     * 启动服务器
     */
    @PostConstruct
    public void start() throws InterruptedException {
        bossGroup = new NioEventLoopGroup();
        workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();

                            // HTTP编解码器
                            pipeline.addLast(new HttpServerCodec());
                            // 块状写入处理器
                            pipeline.addLast(new ChunkedWriteHandler());
                            // HTTP对象聚合器
                            pipeline.addLast(new HttpObjectAggregator(65536));
                            // 心跳检测 (读空闲600秒，写空闲300秒，读写空闲600秒)
                            pipeline.addLast(new IdleStateHandler(600, 300, 600, TimeUnit.SECONDS));
                            // 心跳处理
                            pipeline.addLast(new HeartBeatServerHandler());
                            // WebSocket协议处理器
                            pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
                            // 自定义聊天处理器
                            pipeline.addLast(chatServerHandler);
                        }
                    });

            ChannelFuture future = bootstrap.bind(port).sync();
            channel = future.channel();
            log.info("Netty Chat Server started on port {}", port);
        } catch (InterruptedException e) {
            log.error("Failed to start Netty Chat Server", e);
            throw e;
        }
    }

    /**
     * 关闭服务器
     */
    @PreDestroy
    public void stop() {
        if (channel != null) {
            channel.close();
        }
        if (workerGroup != null) {
            workerGroup.shutdownGracefully();
        }
        if (bossGroup != null) {
            bossGroup.shutdownGracefully();
        }
        log.info("Netty Chat Server stopped");
    }
}